﻿/*========================== 
 * @author 郑金泉
 * @desc XML实用工具
 * ========================= */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Obsidian.Utils
{
    public class XmlUtil
    {

        public static bool TryGetNode(XmlDocument xmlDoc, string xpath, out XmlNode xmlNode)
        {
            xmlNode = xmlDoc.SelectSingleNode(xpath);
            return xmlNode != null;
        }

        public static bool TryGetAttrValue(XmlNode node, string attrName, out string value)
        {
            XmlAttribute attr = node.Attributes[attrName];
            if (attr == null)
            {
                value = null;
                return false;
            }
            value = attr.Value.Trim();
            return true;
        }

        public static bool TryGetAttrBool(XmlNode node, string attrName, out bool value)
        {
            value = false;
            string val;
            if (!TryGetAttrValue(node, attrName, out val))
                return false;
            if (!bool.TryParse(val, out value))
                return false;
            return true;
        }

        public static bool TryGetAttrInt(XmlNode node, string attrName, out int value)
        {
            value = -1;
            string val;
            if (!TryGetAttrValue(node, attrName, out val))
                return false;
            if (!int.TryParse(val, out value))
                return false;
            return true;
        }
    }
}
